package com.school.aftersalemanagement.app;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.util.Log;
import android.widget.Toast;

import com.school.aftersalemanagement.controller.ui.main.MainActivity;
import com.school.aftersalemanagement.global.UserConfig;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.message.lib.BuildConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

/**
 * Created by winkyle on 2017/10/28.
 */

public class MyApplication extends MultiDexApplication {

    public static Context aContext;
   // public PreferencesUtils preferencesUtils;

    @Override
    public void onCreate() {
        super.onCreate();

//       com.wanjian.sak.LayoutManager.init(this);

//      initCLog();
//
        initAnalytics();
//
        initRetrofit();
//
        initPush();
//

        initokhttp(getApplicationContext(), "a", "a");

    //    preferencesUtils = new PreferencesUtils(this);
//        ZXingLibrary.initDisplayOpinion(this);
        instance = this;
    }


    /**打开的activity**/
    private List<Activity> activities = new ArrayList<Activity>();
    /**应用实例**/
    private static MyApplication instance;
    /**
     *  获得实例
     * @return
     */
    public static MyApplication getInstance(){
        return instance;
    }
    /**
     * 新建了一个activity
     * @param activity
     */
    public void addActivity(Activity activity){
        activities.add(activity);
    }
    /**
     *  结束指定的Activity
     * @param activity
     */
    public void finishActivity(Activity activity){
        if (activity!=null) {
            this.activities.remove(activity);
            activity.finish();
            activity = null;
        }
    }
    /**
     * 应用退出，结束所有的activity
     */
    public void exit(){
        for (Activity activity : activities) {
            if (activity!=null) {
                activity.finish();
            }
        }
        System.exit(0);
    }
    /**
     * 关闭Activity列表中的所有Activity*/
    public void finishActivity(){
        for (Activity activity : activities) {
            if (null != activity) {
                activity.finish();
            }
        }
        //杀死该应用进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public static void initokhttp(Context context, String key, String value) {
     //   if (!key.equals("a")) new UserService(context).setCookie(value);
        CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(context));
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(20000L, TimeUnit.MILLISECONDS)
                .readTimeout(20000L, TimeUnit.MILLISECONDS)
                .addInterceptor(new LoggerInterceptor("TAG====="))
                .cookieJar(cookieJar)
                //其他配置
                .build();
        OkHttpUtils.initClient(okHttpClient);
    }

    private void initPush() {
        //如需手动获取device token，可以调用mPushAgent.getRegistrationId()方法
        PushAgent mPushAgent = PushAgent.getInstance(this);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                UserConfig.getInstance(getApplicationContext()).setDeviceToken(deviceToken);
                Log.d("pushonSucceed",UserConfig.getInstance(getApplicationContext()).getDeviceToken());
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.d("pushonFailure " , s + " " + s1);
            }
        });
        mPushAgent.setDebugMode(BuildConfig.DEBUG);
        mPushAgent.setDisplayNotificationNumber(0);
        //自定义通知打开动作
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
               Toast.makeText(getApplicationContext(), "dealWithCustomAction", Toast.LENGTH_SHORT).show();
//                Intent intent=new Intent();
//                intent.setClass(context, MainActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER); //声音
        mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SERVER);//呼吸灯
        mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SERVER);//振动
    }


    private void initRetrofit() {
//
//        aContext = this;
//        //初始化网络请求工具
//        APIFactory.getInstance().init(this);
//
    }
//
    private void initAnalytics() {
        MobclickAgent.setDebugMode(true);

    }
//
//
//    private void initCLog() {
//        String environment = "";
//
//        if (environment.equals("production")) {
//            CLog.setLogLevel(CLog.LEVEL_ERROR);
//        } else if (environment.equals("beta")) {
//            CLog.setLogLevel(CLog.LEVEL_WARNING);
//        } else {
//            // development
//            CLog.setLogLevel(CLog.LEVEL_VERBOSE);
//        }
//
//        CubeDebug.DEBUG_IMAGE = true;
//        PtrFrameLayout.DEBUG = false;
//
//        ImageLoaderFactory.setDefaultImageReSizer(DemoDuiTangImageReSizer.getInstance());
//        ImageLoaderFactory.setDefaultImageLoadHandler(new PtrImageLoadHandler());
//        String dir = "request-cache";
//        // ImageLoaderFactory.init(this);
//        RequestCacheManager.init(this, dir, 1024 * 10, 1024 * 10);
//        Cube.onCreate(this);
//
//    }
//

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}

